<?php

namespace Rblog\Module\Admin\Controller;

class User extends Common {

    public function __construct() {
        parent::__construct();
    }
    
    /**
     * 登录博客后台管理模块动作
     */
    public function login() {
        if ( ! $this->request->isPost() ) {
            //提交登录信息进行登录操作
            
            // 刚进入登录页面，显示登录表单
            $this->view->display();
        } else {
            try {
                //检查表单是否填写完成
                if ( ! $this->request->input( 'name', 'p' ) ) {
                    throw new \Exception( '请输入用户名' );
                }
                if ( ! $this->request->input( 'password', 'p' ) ) {
                    throw new \Exception( '请输入密码' );
                }

                $name = trim( $this->request->input( 'name', 'p' ) );
                $password = trim( $this->request->input( 'password', 'p' ) );

                //检查用户信息是否为已注册用户，准许登录
                $userLib = new \Rblog\Module\Admin\Lib\User();
                $result = $userLib->logCheck( $name, $password );
                if ( $result == -1 ) {
                    throw new \Exception( '用户名不存在' );
                }
                if ( $result == -2 ) {
                    throw new \Exception( '密码不符' );
                }
                
                session_start();
                //验证码是否正确
                $verifyCode = $this->request->input( 'verifyCode', 'p');
                if ( strcasecmp( $verifyCode, $_SESSION['verify_code'] ) != 0 ) {
                    throw new \Exception( '验证码不正确' );
                }
                session_destroy();
                
                //通过用户名和密码提取用户id（userID)，设置用户id cookie 变量
                $db = \Rexzy::model( 'User' );
                $userid = $db->userid( $name );
                
                $userLib->login( 'userid', $userid, 1800 );
                
                //信息符合，跳转到简历管理页面
                $this->response->location( \Rexzy::url( 'admin/index' ) );
            } catch ( \Exception  $e) {
                $error = $e->getMessage();
                $this->view->assign( 'error', $error );
                $this->view->display();
            }
        } 
    }
    
    /**
     * 登出
     */
    public function logout() {
        $userLib = new \Rblog\Module\Admin\Lib\User();
        $userLib->login( 'userid' );
        $this->response->location( \Rexzy::url( 'user/login' ) );
    }
    
    
    /**
     * 验证码图片
     */
    public function verify() {
        $img = imagecreatetruecolor( 150, 44);
        $backgroundColor = imagecolorallocate( $img, rand(200, 255), rand(200, 255), rand(200, 255) );
        imagefill( $img, 0, 0, $backgroundColor );
        
        $fontArray = array_merge( range( 0, 9), range( 'A', 'Z'), range( 'a', 'z' ) );
        shuffle( $fontArray );
        $code = array_slice( $fontArray, 0, 4 );
  
        session_start();
        $_SESSION['verify_code'] = implode( '', $code );
        
        foreach( $code as $key => $val ) {
            if ( $key == 0 ) {
                $start = 30;
            } else {
                $start = 25 * ( $key + 1 );
            }
            $fontColor = imagecolorallocate( $img, rand( 0, 200 ), rand( 0, 200 ), rand( 0, 200 ) );
            imagettftext( $img, 22, rand( 0, 60 ), $start, 35, $fontColor, REXZY_ROOT . '/Tool/arial.ttf', $val);
        }
        
        header("Content-Type: image/png");
        imagepng( $img );
    }
    
    /**
     * 第三方登录
     */
    public function openid() {
        $code = $this->request->input( 'code', 'g' );
        $path = "https://api.weibo.com/oauth2/access_token";
        $params = array(
            'client_id' => 1391253594,
            'client_secret' => "8ae846bdbb8529cbdcc58d14265b3eb9",
            'grant_type' => "authorization_code",
            'code' => $code,
            'redirect_uri' => \Rexzy::getConfig( 'url' ),
        );
        $tokens = $this->_request( $path, 'post', $params );
        $mesgPath = "https://api.weibo.com/2/users/show.json";
        $mesgParams = array(
            'access_token' => $tokens['access_token'],
            'uid' => $tokens['uid'],
        );
        $mesg = $this->_request( $mesgPath, 'get', $mesgParams );
        
        $userData = \Rexzy::model( 'exuser' );
        if ( empty( $userData->select( 'openid', array( 'openid' => $mesg['id'] ) ) ) ) {
            $userid = $userData->insert( array(
                'name' => $mesg['screen_name'],
                'avatar' => $mesg['profile_image_url'],
                'openid' => $mesg['id']
            ));
            if ( $userid ) {
                $OIDUData = \Rexzy::model( 'openuser' );
                $OIDUData->insert( array(
                    'openid' => $mesg['id'],
                    'name' => $mesg['name'],
                    'screen_name' => $mesg['screen_name'],
                    'avatar' => $mesg['profile_image_url'],
                    'allmesg' => json_encode( $mesg ),
                    'userid' => $userid
                ));
            }
        }
        echo "登录成功！";
    }
    
    private function _request( $path, $method = 'get', $params = array(), $type = 'json' ) {
        // 1. 初始化
        
        
        $ch = curl_init();
        $params = (is_array($params)) ? http_build_query($params) : $params; 
        if( $method === 'put' ) {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        } else if( $method === 'post' ) {
            curl_setopt($ch, CURLOPT_POST, 1);
            // 把post的变量加上
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        } else if( $method === 'delete' ) {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
        } else { // get
            $join = strpos( $path, '?' ) ? '&' : '?';
            $path = $path . $join . $params ;
        }
        // 2. 设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $path);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//        curl_setopt($ch, CURLOPT_HEADER, 1);
        
        
        // 3. 执行并获取HTML文档内容
        $response = curl_exec($ch);
        
        // 4. 释放curl句柄
        curl_close($ch);
        if( $type == 'json' ) {
            return json_decode($response, true);
        }
        return $response;
    }
}
